<template>
  <div class="login-view">
    <div class="login-container">
      <div class="login-card">
        <!-- 头部 -->
        <div class="login-header">
          <h1>{{ isLogin ? '登录' : '注册' }}</h1>
          <p>{{ isLogin ? '欢迎回来，请登录您的账户' : '创建新账户，开始您的笔记之旅' }}</p>
        </div>

        <!-- 登录表单 -->
        <el-form
          v-if="isLogin"
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="用户名/邮箱/手机号"
              prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item v-if="captchaEnabled" prop="code">
            <div class="captcha-wrapper">
              <el-input
                v-model="loginForm.code"
                placeholder="验证码"
                prefix-icon="Key"
                style="flex: 1"
              />
              <img
                :src="captchaImg"
                @click="getCaptchaImage"
                class="captcha-img"
                alt="验证码"
                title="点击刷新验证码"
              />
            </div>
          </el-form-item>
          
          <el-form-item>
            <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
              <el-link type="primary" @click="showForgotPassword = true">忘记密码？</el-link>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              style="width: 100%"
              :loading="loginLoading"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 注册表单 -->
        <el-form
          v-else
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          size="large"
          @submit.prevent="handleRegister"
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="用户名"
              prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
              prefix-icon="Message"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="emailCode">
            <div class="email-code-wrapper">
              <el-input
                v-model="registerForm.emailCode"
                placeholder="邮箱验证码"
                prefix-icon="Key"
                style="flex: 1"
              />
              <el-button
                :disabled="emailCodeCountdown > 0"
                @click="sendEmailVerifyCode"
                :loading="sendingEmailCode"
              >
                {{ emailCodeCountdown > 0 ? `${emailCodeCountdown}s` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
          
          <el-form-item prop="agreement">
            <el-checkbox v-model="registerForm.agreement">
              我已阅读并同意
              <el-link type="primary" @click="showTerms = true">《用户协议》</el-link>
              和
              <el-link type="primary" @click="showPrivacy = true">《隐私政策》</el-link>
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              style="width: 100%"
              :loading="registerLoading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 切换登录/注册 -->
        <div class="switch-mode">
          <span>{{ isLogin ? '还没有账户？' : '已有账户？' }}</span>
          <el-link type="primary" @click="toggleMode">
            {{ isLogin ? '立即注册' : '立即登录' }}
          </el-link>
        </div>

        <!-- 第三方登录 -->
        <div class="social-login" v-if="isLogin">
          <div class="divider">
            <span>或</span>
          </div>
          <div class="social-buttons">
            <el-button class="social-btn github" @click="socialLogin('github')">
              <i class="fab fa-github"></i>
              GitHub
            </el-button>
            <el-button class="social-btn wechat" @click="socialLogin('wechat')">
              <i class="fab fa-weixin"></i>
              微信
            </el-button>
            <el-button class="social-btn qq" @click="socialLogin('qq')">
              <i class="fab fa-qq"></i>
              QQ
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="showForgotPassword"
      title="重置密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form ref="forgotFormRef" :model="forgotForm" :rules="forgotRules" size="large">
        <el-form-item prop="email">
          <el-input
            v-model="forgotForm.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        <el-form-item prop="code">
          <div class="email-code-wrapper">
            <el-input
              v-model="forgotForm.code"
              placeholder="邮箱验证码"
              prefix-icon="Key"
              style="flex: 1"
            />
            <el-button
              :disabled="forgotCodeCountdown > 0"
              @click="sendForgotCode"
              :loading="sendingForgotCode"
            >
              {{ forgotCodeCountdown > 0 ? `${forgotCodeCountdown}s` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="forgotForm.newPassword"
            type="password"
            placeholder="新密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForgotPassword = false">取消</el-button>
        <el-button type="primary" :loading="resetLoading" @click="handleResetPassword">
          重置密码
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户协议对话框 -->
    <el-dialog v-model="showTerms" title="用户协议" width="600px">
      <div class="terms-content">
        <h3>1. 服务条款</h3>
        <p>欢迎使用我们的笔记服务。通过访问和使用本服务，您同意遵守以下条款和条件。</p>
        
        <h3>2. 用户责任</h3>
        <p>您有责任确保您的账户信息准确无误，并保护您的登录凭据。您不得使用本服务进行任何非法活动。</p>
        
        <h3>3. 内容政策</h3>
        <p>您发布的内容必须遵守相关法律法规，不得包含违法、有害或侵犯他人权利的内容。</p>
        
        <h3>4. 服务变更</h3>
        <p>我们保留随时修改或终止服务的权利，恕不另行通知。</p>
      </div>
    </el-dialog>

    <!-- 隐私政策对话框 -->
    <el-dialog v-model="showPrivacy" title="隐私政策" width="600px">
      <div class="privacy-content">
        <h3>1. 信息收集</h3>
        <p>我们收集您提供的个人信息，包括但不限于用户名、邮箱地址等。</p>
        
        <h3>2. 信息使用</h3>
        <p>我们使用收集的信息来提供和改进我们的服务，以及与您沟通。</p>
        
        <h3>3. 信息保护</h3>
        <p>我们采取适当的安全措施来保护您的个人信息免受未经授权的访问、使用或披露。</p>
        
        <h3>4. 信息共享</h3>
        <p>除非法律要求或您明确同意，我们不会与第三方共享您的个人信息。</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { login, register, getCaptcha, sendEmailCode, resetPassword } from '@/api/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const forgotFormRef = ref<FormInstance>()

// 页面状态
const isLogin = ref(true)
const loginLoading = ref(false)
const registerLoading = ref(false)
const resetLoading = ref(false)
const captchaEnabled = ref(true)
const captchaImg = ref('')
const showForgotPassword = ref(false)
const showTerms = ref(false)
const showPrivacy = ref(false)

// 邮箱验证码倒计时
const emailCodeCountdown = ref(0)
const sendingEmailCode = ref(false)
const forgotCodeCountdown = ref(0)
const sendingForgotCode = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
  rememberMe: false
})

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  emailCode: '',
  agreement: false
})

// 忘记密码表单
const forgotForm = reactive({
  email: '',
  code: '',
  newPassword: ''
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线和中文', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  emailCode: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const forgotRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ]
}

// 获取验证码
const getCaptchaImage = async () => {
  try {
    const response = await getCaptcha()
    captchaImg.value = 'data:image/gif;base64,' + response.img
    loginForm.uuid = response.uuid
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true
      try {
        const response = await userStore.loginAction({
          username: loginForm.username,
          password: loginForm.password
        })
        
        ElMessage.success('登录成功')
        
        // 跳转到目标页面或首页
        const redirect = route.query.redirect as string
        router.push(redirect || '/')
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败')
        if (captchaEnabled.value) {
          getCaptchaImage()
        }
      } finally {
        loginLoading.value = false
      }
    }
  })
}

// 发送邮箱验证码
const sendEmailVerifyCode = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  
  sendingEmailCode.value = true
  try {
    await sendEmailCode(registerForm.email)
    ElMessage.success('验证码已发送')
    startCountdown('email')
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送失败')
  } finally {
    sendingEmailCode.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true
      try {
        const response = await register({
          username: registerForm.username,
          email: registerForm.email,
          password: registerForm.password,
          emailCode: registerForm.emailCode
        })
        
        if (response.code === 200) {
          ElMessage.success('注册成功，请登录')
          isLogin.value = true
          // 清空注册表单
          Object.assign(registerForm, {
            username: '',
            email: '',
            password: '',
            confirmPassword: '',
            emailCode: '',
            agreement: false
          })
        } else {
          ElMessage.error(response.msg || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error('注册失败')
      } finally {
        registerLoading.value = false
      }
    }
  })
}

// 发送忘记密码验证码
const sendForgotCode = async () => {
  if (!forgotForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  
  sendingForgotCode.value = true
  try {
    const response = await sendEmailVerifyCode(forgotForm.email)
    if (response.code === 200) {
      ElMessage.success('验证码已发送')
      startCountdown('forgot')
    } else {
      ElMessage.error(response.msg || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送失败')
  } finally {
    sendingForgotCode.value = false
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  if (!forgotFormRef.value) return
  
  await forgotFormRef.value.validate(async (valid) => {
    if (valid) {
      resetLoading.value = true
      try {
        const response = await resetPassword({
          email: forgotForm.email,
          code: forgotForm.code,
          newPassword: forgotForm.newPassword
        })
        
        if (response.code === 200) {
          ElMessage.success('密码重置成功，请重新登录')
          showForgotPassword.value = false
          // 清空表单
          Object.assign(forgotForm, {
            email: '',
            code: '',
            newPassword: ''
          })
        } else {
          ElMessage.error(response.msg || '重置失败')
        }
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置失败')
      } finally {
        resetLoading.value = false
      }
    }
  })
}

// 开始倒计时
const startCountdown = (type: 'email' | 'forgot') => {
  const countdown = type === 'email' ? emailCodeCountdown : forgotCodeCountdown
  countdown.value = 60
  
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  // 清空表单
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
}

// 第三方登录
const socialLogin = (provider: string) => {
  ElMessage.info(`${provider} 登录功能开发中...`)
}

// 页面初始化
onMounted(() => {
  // 检查是否已登录
  if (userStore.isLoggedIn) {
    const redirect = route.query.redirect as string
    router.push(redirect || '/')
    return
  }
  
  // 获取验证码
  if (captchaEnabled.value) {
    getCaptchaImage()
  }
  
  // 检查URL参数
  const mode = route.query.mode
  if (mode === 'register') {
    isLogin.value = false
  }
})
</script>

<style scoped>
.login-view {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 2rem;
  color: #303133;
  margin-bottom: 10px;
}

.login-header p {
  color: #606266;
  font-size: 0.9rem;
}

.captcha-wrapper,
.email-code-wrapper {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-img {
  width: 100px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.switch-mode {
  text-align: center;
  margin-top: 20px;
  color: #606266;
}

.social-login {
  margin-top: 30px;
}

.divider {
  text-align: center;
  margin: 20px 0;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.divider span {
  background: white;
  padding: 0 15px;
  color: #909399;
  font-size: 0.9rem;
}

.social-buttons {
  display: flex;
  gap: 10px;
}

.social-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.social-btn.github {
  background: #333;
  border-color: #333;
  color: white;
}

.social-btn.wechat {
  background: #07c160;
  border-color: #07c160;
  color: white;
}

.social-btn.qq {
  background: #12b7f5;
  border-color: #12b7f5;
  color: white;
}

.terms-content,
.privacy-content {
  max-height: 400px;
  overflow-y: auto;
  line-height: 1.6;
}

.terms-content h3,
.privacy-content h3 {
  color: #303133;
  margin: 20px 0 10px;
}

.terms-content p,
.privacy-content p {
  color: #606266;
  margin-bottom: 15px;
}

@media (max-width: 480px) {
  .login-view {
    padding: 10px;
  }
  
  .login-card {
    padding: 30px 20px;
  }
  
  .login-header h1 {
    font-size: 1.5rem;
  }
  
  .social-buttons {
    flex-direction: column;
  }
  
  .captcha-wrapper,
  .email-code-wrapper {
    flex-direction: column;
    align-items: stretch;
  }
  
  .captcha-img {
    width: 100%;
    height: 50px;
  }
}
</style>